import { type SelectProps, TreeSelect } from 'antd';
import { useEffect, useState } from 'react';

import { Region } from '@/pages/management/system/region/type';
import { useRegions } from '@/store/userStore';

export interface RegionSelectProps<ValueType = any>
  extends Omit<SelectProps<ValueType | ValueType[]>, 'options' | 'children'> {
  canParentSelect?: boolean;
}

export function RegionSelect({
  canParentSelect = true,
  placeholder = '请选择地区',
  ...props
}: RegionSelectProps) {
  const [value, setValue] = useState<string>();
  const [treeData, setTreeData] = useState<Region[]>();

  const onChange = (newValue: string) => {
    setValue(newValue);
  };
  // 传参： treeData: 树形数据
  const addKey = (data?: any) => {
    if (data) {
      return data.map((item: any) => ({
        ...item,
        disabled: item.children?.length > 0,
        children: item.children ? addKey(item.children) : [],
      }));
    }
    return [];
  };
  const regions = useRegions();
  useEffect(() => {
    setTreeData(regions);
  }, [regions]);

  return (
    <TreeSelect
      style={{ width: '100%' }}
      value={value}
      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
      placeholder={placeholder}
      treeData={canParentSelect ? treeData : addKey(treeData)}
      fieldNames={{ label: 'name', value: 'code', children: 'children' }}
      onChange={onChange}
      popupMatchSelectWidth={false}
      {...props}
    />
  );
}
